import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Typography,
  Spin,
  Tag,
  Collapse,
  Space,
  Alert,
} from 'antd'
import {
  LinkOutlined,
  FileTextOutlined,
  CiOutlined,
  InfoOutlined,
  DatabaseOutlined,
} from '@ant-design/icons'
import './style.less'

// 在组件顶部、接口定义后，添加表格数据源的类型
// 1. 环境信息表格数据类型
interface EnvTableItem {
  key: string
  name: string
  value: string | number
  displayValue: React.ReactNode | string | number
}

// 2. 性能指标表格数据类型
interface MetricsTableItem {
  key: string
  name: string
  value: string | number
  description: string
}

// 3. 资源加载表格数据类型
interface ResourceTableItem {
  key: string
  name: string
  loadTime: string
  type: string
}

// 4. 埋点事件表格数据类型
interface EventTableItem {
  key: string
  eventName: string
  eventType: string
  timestamp: string
  pageUrl: string
  data: string
}

// 类型定义保持与performance.ts一致
interface PerformanceMetrics {
  pageLoadTime?: number
  firstPaint?: number
  firstContentfulPaint?: number
  domInteractive?: number
  domComplete?: number
  resourceLoadTime?: Record<string, number>
  memoryUsage?: number
  customMarks?: Record<string, number>
}

interface TrackEventData {
  buttonId?: string // 按钮ID（如 send-performance-btn）
  actionDesc?: string // 操作描述
  duration?: number // 耗时（毫秒）
  fromTab?: string // 切换前的Tab（如 Tab 切换事件）
  toTab?: string // 切换后的Tab（如 Tab 切换事件）
  [key: string]: unknown // 允许扩展字段，但用 unknown 替代 any（更安全）
}

interface TrackEvent {
  eventName: string
  eventType: string
  timestamp: number
  pageUrl: string
  userId?: string
  data?: TrackEventData
}

interface EnvInfo {
  timestamp: number
  userId: string
  pageUrl: string
  userAgent: string
  browser: string
}

interface RealPerformanceData {
  metrics: PerformanceMetrics
  events: TrackEvent[]
  env?: EnvInfo
}

interface DataDashboardProps {
  realPerformanceData?: RealPerformanceData
  isDataReady: boolean
}

const { Title, Paragraph } = Typography
const { Panel } = Collapse

const DataDashboard: React.FC<DataDashboardProps> = ({
  realPerformanceData,
  isDataReady = false,
}) => {
  const [loading, setLoading] = useState<boolean>(true)
  const [metricsTableData, setMetricsTableData] = useState<MetricsTableItem[]>(
    []
  )
  const [eventsTableData, setEventsTableData] = useState<EventTableItem[]>([])
  const [resourceData, setResourceData] = useState<ResourceTableItem[]>([])
  const [envData, setEnvData] = useState<EnvTableItem[]>([])
  const [error, setError] = useState<string | null>(null)

  // 数据处理主逻辑，添加详细日志
  useEffect(() => {
    console.log('===== DataDashboard 数据处理开始 =====')
    console.log('接收的 isDataReady:', isDataReady)
    console.log('接收的 realPerformanceData:', realPerformanceData)

    // 重置状态
    setMetricsTableData([])
    setEventsTableData([])
    setResourceData([])
    setEnvData([])
    setError(null)
    setLoading(true)

    // 检查数据是否准备好
    if (!isDataReady) {
      console.log('数据未准备好 (isDataReady 为 false)')
      const timer = setTimeout(() => {
        setLoading(false)
        setError('等待数据准备...请点击"发送性能数据"按钮')
      }, 1000)
      return () => clearTimeout(timer)
    }

    // 检查数据是否存在
    if (!realPerformanceData) {
      console.error('realPerformanceData 为 undefined 或 null')
      setLoading(false)
      setError('未接收到性能数据，请检查数据传递是否正确')
      return
    }

    try {
      const { metrics, events, env } = realPerformanceData

      // 验证核心数据结构
      console.log(' metrics 存在:', !!metrics)
      console.log(' events 存在:', !!events)
      console.log(' env 存在:', !!env)

      // 处理环境数据
      if (!env) {
        console.warn('env 数据缺失')
        setEnvData([
          {
            key: 'warning',
            name: '警告',
            displayValue: '未获取到环境信息',
            value: '未获取到环境信息',
          },
        ])
      } else {
        const convertedEnv = convertEnvToTableData(env)
        console.log('转换后的环境数据:', convertedEnv)
        setEnvData(convertedEnv)
      }

      // 处理性能指标数据
      if (!metrics) {
        console.warn('metrics 数据缺失')
        setMetricsTableData([
          {
            key: 'warning',
            name: '警告',
            value: '未获取到性能指标数据',
            description: '',
          },
        ])
      } else {
        const convertedMetrics = convertMetricsToTableData(metrics)
        console.log('转换后的性能指标数据:', convertedMetrics)
        setMetricsTableData(convertedMetrics)
      }

      // 处理资源数据
      if (
        !metrics?.resourceLoadTime ||
        Object.keys(metrics.resourceLoadTime).length === 0
      ) {
        console.warn('resourceLoadTime 数据缺失或为空')
        setResourceData([
          { key: 'warning', name: '无资源数据', loadTime: '', type: '提示' },
        ])
      } else {
        const convertedResources = convertResourcesToTableData(
          metrics.resourceLoadTime
        )
        console.log('转换后的资源数据:', convertedResources)
        setResourceData(convertedResources)
      }

      // 处理事件数据
      if (!events || events.length === 0) {
        console.warn('events 数据缺失或为空')
        setEventsTableData([
          {
            key: 'warning',
            eventName: '无事件数据',
            eventType: '提示',
            timestamp: '',
            pageUrl: '',
            data: '未记录任何事件',
          },
        ])
      } else {
        const convertedEvents = convertEventsToTableData(events)
        console.log('转换后的事件数据:', convertedEvents)
        setEventsTableData(convertedEvents)
      }

      // 所有数据处理完成
      setLoading(false)
      console.log('===== DataDashboard 数据处理完成 =====')
    } catch (err) {
      console.error('数据处理出错:', err)
      setLoading(false)
      setError(
        `数据处理出错: ${err instanceof Error ? err.message : '未知错误'}`
      )
    }
  }, [isDataReady, realPerformanceData,])

  // 转换环境信息
  const convertEnvToTableData = (env: EnvInfo): EnvTableItem[] => {
    return [
      {
        key: 'timestamp',
        name: 'timestamp',
        value: env.timestamp,
        displayValue: new Date(env.timestamp).toLocaleString(),
      },
      {
        key: 'userId',
        name: 'userId',
        value: env.userId,
        displayValue: env.userId,
      },
      {
        key: 'pageUrl',
        name: 'pageUrl',
        value: env.pageUrl,
        displayValue: (
          <div
            style={{
              maxWidth: 500,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {env.pageUrl}
          </div>
        ),
      },
      {
        key: 'browser',
        name: 'browser',
        value: env.browser,
        displayValue: env.browser,
      },
      {
        key: 'userAgent',
        name: 'userAgent',
        value: env.userAgent,
        displayValue: (
          <div
            style={{
              maxWidth: 500,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {env.userAgent}
          </div>
        ),
      },
    ]
  }

  // 转换性能指标
  const convertMetricsToTableData = (
    metrics: PerformanceMetrics
  ): MetricsTableItem[] => {
    return [
      {
        key: 'pageLoadTime',
        name: '页面加载时间(ms)',
        value:
          metrics.pageLoadTime !== undefined
            ? metrics.pageLoadTime < 0
              ? '异常值'
              : `${metrics.pageLoadTime.toFixed(2)} ms`
            : '未采集',
        description: '从导航开始到页面完全加载的时间',
      },
      {
        key: 'firstPaint',
        name: '首次绘制(ms)',
        value:
          metrics.firstPaint !== undefined
            ? `${metrics.firstPaint.toFixed(2)} ms`
            : '未采集',
        description: '浏览器首次绘制像素的时间',
      },
      {
        key: 'firstContentfulPaint',
        name: '首次内容绘制(ms)',
        value:
          metrics.firstContentfulPaint !== undefined
            ? `${metrics.firstContentfulPaint.toFixed(2)} ms`
            : '未采集',
        description: '浏览器首次绘制内容的时间',
      },
      {
        key: 'domInteractive',
        name: 'DOM可交互时间(ms)',
        value:
          metrics.domInteractive !== undefined
            ? `${metrics.domInteractive.toFixed(2)} ms`
            : '未采集',
        description: 'DOM树构建完成，开始响应用户交互的时间',
      },
      {
        key: 'domComplete',
        name: 'DOM完成时间(ms)',
        value:
          metrics.domComplete !== undefined
            ? `${metrics.domComplete.toFixed(2)} ms`
            : '未采集',
        description: '所有DOM解析和资源加载完成的时间',
      },
      {
        key: 'memoryUsage',
        name: '内存使用量(byte)',
        value:
          metrics.memoryUsage !== undefined
            ? `${(metrics.memoryUsage / 1024 / 1024).toFixed(2)} MB`
            : '未支持',
        description: '当前页面使用的JavaScript堆内存',
      },
      {
        key: 'customMarksCount',
        name: '自定义标记数',
        value: metrics.customMarks
          ? Object.keys(metrics.customMarks).length
          : 0,
        description: '自定义性能标记的总数',
      },
    ]
  }

  // 转换资源数据
  const convertResourcesToTableData = (
    resourceLoadTime?: Record<string, number>
  ) => {
    if (!resourceLoadTime) return []

    return Object.entries(resourceLoadTime).map(([name, time]) => ({
      key: `resource-${name}`,
      name: name,
      loadTime: `${time.toFixed(2)} ms`,
      type: getResourceType(name),
    }))
  }

  // 转换事件数据
  const convertEventsToTableData = (events: TrackEvent[]): EventTableItem[] => {
    return events.map((event, index) => ({
      key: `event-${index}-${event.eventName}`,
      eventName: event.eventName,
      eventType: event.eventType,
      timestamp: new Date(event.timestamp).toLocaleTimeString(),
      pageUrl:
        event.pageUrl.length > 50
          ? `${event.pageUrl.slice(0, 50)}...`
          : event.pageUrl,
      data: event.data ? JSON.stringify(event.data) : '无',
    }))
  }

  // 判断资源类型
  const getResourceType = (name: string):string => {
    if (name.endsWith('.js')) return 'JavaScript'
    if (name.endsWith('.css') || name.endsWith('.less')) return '样式表'
    if (name.match(/\.(png|jpg|jpeg|gif|svg)$/i)) return '图片'
    if (
      name.endsWith('.woff') ||
      name.endsWith('.woff2') ||
      name.endsWith('.ttf')
    )
      return '字体'
    if (name.includes('api') || name.includes('json')) return 'API请求'
    return '其他资源'
  }

  // 表格列定义
  const envColumns = [
    {
      title: '索引',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (name: string) => <code>{name}</code>,
    },
    {
      title: '值',
      dataIndex: 'displayValue',
      key: 'value',
      render: (displayValue: React.ReactNode, record: EnvTableItem) =>
        displayValue || record.value,
    },
  ]

  const metricsColumns = [
    {
      title: '索引',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (name: string) => <code>{name}</code>,
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
      width: 150,
      render: (value: string | number) => (
        <span
          style={{
            color:
              value === '未采集'
                ? '#888'
                : value === '异常值'
                ? '#f5222d'
                : '#000',
          }}
        >
          {value}
        </span>
      ),
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
    },
  ]

  const resourceColumns = [
    {
      title: '资源名称',
      dataIndex: 'name',
      key: 'name',
      render: (name:string) => (
        <div
          style={{
            maxWidth: 300,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          <code>{name}</code>
        </div>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => <Tag >{type}</Tag>,
    },
    {
      title: '加载时间',
      dataIndex: 'loadTime',
      key: 'loadTime',
      width: 120,
    },
  ]

  const eventsColumns = [
    {
      title: '事件名称',
      dataIndex: 'eventName',
      key: 'eventName',
      width: 180,
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      key: 'eventType',
      width: 140,
      render: (type: string) => (
        <Tag  color='blue'>
          {type}
        </Tag>
      ),
    },
    {
      title: '触发时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 150,
    },
    {
      title: '页面URL',
      dataIndex: 'pageUrl',
      key: 'pageUrl',
      render: (url: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <LinkOutlined  />
          <span>{url}</span>
        </div>
      ),
    },
    {
      title: '额外数据',
      dataIndex: 'data',
      key: 'data',
      render: (data: string) => (
        <div
          style={{
            maxWidth: 300,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            fontSize: '12px',
            color: '#666',
          }}
        >
          {data}
        </div>
      ),
    },
  ]

  return (
    <div className='data-dashboard'>
      <Title level={2}>性能监控数据</Title>
      <Paragraph className='dashboard-intro'>
        以下数据应与控制台输出一致，包含环境信息、核心性能指标、资源加载耗时和埋点事件记录
      </Paragraph>

      {/* 错误提示 */}
      {error && (
        <Alert
          message='数据加载提示'
          description={error}
          type='warning'
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      {loading ? (
        <div
          className='loading-container'
          style={{ textAlign: 'center', padding: '50px 0' }}
        >
          <Spin size='large' />
          <p style={{ marginTop: 16 }}>加载性能数据中...</p>
        </div>
      ) : (
        <Collapse
          defaultActiveKey={['env', 'metrics', 'resources', 'events']}
          bordered
          expandIconPosition='left'
          style={{ marginTop: 16 }}
        >
          {/* 环境信息面板 */}
          <Panel
            header={
              <Space size='middle'>
                <InfoOutlined />
                <span>环境信息</span>
              </Space>
            }
            key='env'
          >
            <Card bordered={false}>
              <Table
                columns={envColumns}
                dataSource={envData}
                pagination={false}
                rowKey='key'
                size='small'
                scroll={{ x: 'max-content' }}
                showHeader={false}
              />
            </Card>
          </Panel>

          {/* 核心性能指标面板 */}
          <Panel
            header={
              <Space size='middle'>
                <CiOutlined />
                <span>核心性能指标</span>
              </Space>
            }
            key='metrics'
          >
            <Card bordered={false}>
              <Table
                columns={metricsColumns}
                dataSource={metricsTableData}
                pagination={false}
                rowKey='key'
                size='small'
                scroll={{ x: 'max-content' }}
              />
            </Card>
          </Panel>

          {/* 资源加载耗时面板 */}
          <Panel
            header={
              <Space size='middle'>
                <FileTextOutlined />
                <span>资源加载耗时</span>
              </Space>
            }
            key='resources'
          >
            <Card bordered={false}>
              <Table
                columns={resourceColumns}
                dataSource={resourceData}
                pagination={{ pageSize: 15 }}
                rowKey='key'
                size='small'
                scroll={{ x: 'max-content' }}
              />
            </Card>
          </Panel>

          {/* 埋点事件记录面板 */}
          <Panel
            header={
              <Space size='middle'>
                <DatabaseOutlined />
                <span>埋点事件记录</span>
              </Space>
            }
            key='events'
          >
            <Card bordered={false}>
              <Table
                columns={eventsColumns}
                dataSource={eventsTableData}
                pagination={{ pageSize: 10 }}
                rowKey='key'
                size='small'
                scroll={{ x: 'max-content' }}
              />
            </Card>
          </Panel>
        </Collapse>
      )}
    </div>
  )
}

export default DataDashboard
